import axios from 'axios'

axios.interceptors.request.use(config => {
  console.log(config.headers)
  if (config.heasers) {
    config.heasers.token = localStorage.getItem('token')
  } else {
    config.headers = {
      token: localStorage.getItem('token')
    }
  }
  return config
}, error => {
  return Promise.reject(error)
})

axios.interceptors.response.use(response => {
  if (response.data.error_code === 1210 || response.data.error_code === 0) {
    return response.data.data
  } else {
    return Promise.reject(response.data.msg)
  }
}, error => {
  console.log(error.response)
  // return Promise.resolve(error.response)
})

class HP {
  constructor () {
    this._debugger = false
  };

  _error (msg) {
    console.log(msg)
  }

  prefixUrl (url) {
    if (this._debugger) {
      return `http://www.hysyzxf.top/${url}`
    } else {
      return url
    }
  }

  get (url, reData) {
    url = this.prefixUrl(url)
    this.promise = new Promise((resolve, reject) => {
      axios.get(url, {params: reData})
        .then((data) => {
          resolve(data)
        })
        .catch((data) => {
          this._error(data)
        })
    })
    return this.promise
  }

  put (url, reData) {
    url = this.prefixUrl(url)
    this.promise = new Promise((resolve, reject) => {
      axios.put(url, {params: reData})
        .then((data) => {
          resolve(data)
        })
        .catch((data) => {
          this._error(data)
        })
    })
    return this.promise
  }

  post (url, reData) {
    url = this.prefixUrl(url)
    this.promise = new Promise((resolve, reject) => {
      axios.post(url, reData)
        .then((data) => {
          resolve(data)
        })
        .catch((data) => {
          this._error(data)
        })
    })
    return this.promise
  }

  delete (url, reData) {
    url = this.prefixUrl(url)
    this.promise = new Promise((resolve, reject) => {
      axios.delete(url, {params: reData})
        .then((data) => {
          resolve(data)
        })
        .catch((data) => {
          this._error(data)
        })
    })
    return this.promise
  }
}

export default new HP()
